<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 商品管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <!--表单-->
            <el-form :inline="true" :model="query" class="demo-form-inline">
                <el-button type="primary" @click="onAdd">新增</el-button>

                <el-cascader
                    placeholder="分类"
                    v-model="optionsValue"
                    :options="optionsCategory"
                    :props="{ expandTrigger: 'hover' }"
                    @change="handleCategoryChange"
                ></el-cascader>
                <el-form-item>
                    <el-input v-model="query.name" placeholder="输入商品" style="width: 140px"></el-input>
                </el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form>

            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"                
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="name" label="商品名"></el-table-column>
                <el-table-column label="单价">
                    <template slot-scope="scope">￥{{ scope.row.price }}</template>
                </el-table-column>
                <el-table-column label="图片(查看大图)" align="center">
                    <template slot-scope="scope">
                        <el-image class="table-td-image" :src="`${ApiBaseURL}${scope.row.image}`" :preview-src-list="[`${ApiBaseURL}${scope.row.image}`]"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="sell_point" label="销售亮点"></el-table-column>

                <el-table-column prop="create_time" label="上架时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="recordTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品名">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="分类">
                    <el-input v-model="form.category_id"></el-input>
                </el-form-item>
                <el-form-item label="价格">
                    <el-input v-model="form.price"/>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="form.num"/>
                </el-form-item>
                <el-form-item label="图片">
                    

<el-upload   
    name = "singleFile"
    :action="uploadAction" 
    :limit="1"
    :on-success="handleSuccess"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
  
    list-type="picture">
    <el-button size="small" type="primary" >点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    
</el-upload>                    









                </el-form-item>
                <el-form-item label="销售亮点">
                    <el-input v-model="form.sell_point"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="`${ApiBaseURL}${form.image}`" alt />
              </el-dialog>


    </div>
</template>

<script>
import { getGoodsList, getCategoryOptions ,deleteGoodsById,updateGoods} from '@/api/goods.js';
export default {
    name: 'goods',
    data() {
        return {            
            optionsValue: [],
            optionsCategory: [],
            query: {
                category_id: '',
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            // multipleSelection: [],
            delList: [],
            editVisible: false,
            recordTotal: 0,
            form: {},
            idx: -1,
            id: -1,

            imageUrl: '',

            dialogVisible: false,
		productImgs: [],
		imgLimit: 1,//文件个数
		hideUploadEdit:false,
        fileList:[],
        uploadAction:"http://localhost:5050/upload/single"

        };
    },
    created() {
        this.getTableData();
        this.getDataCategoryOptions();
    },
    computed: {
        ApiBaseURL(){
            return process.env.VUE_APP_BASE_API
        }
    },
    methods: {
        onAdd() {},        
        //分类改变后被调用
        handleCategoryChange() {            
            this.query.category_id = this.optionsValue[1]
            this.getTableData();
        },
        // 获取分类信息数据，初始分类选择组件数据
        async getDataCategoryOptions() {
            let result = await getCategoryOptions();
            this.optionsCategory = result.data;            
        },

        // 获取表格的数据
        async getTableData() {
            let result = await getGoodsList(this.query);
            this.tableData = result.data;
            this.recordTotal = result.recordTotal || 50;
            //处理记录中的图片path = ApiBaseURL + path
            //this.tableData.forEach(element => element.image = this.ApiBaseURL + element.image);
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getTableData();
        },
        // 删除操作
        async handleDelete(index, row) {
            
            try {
                // 二次确认删除
                await this.$confirm('确定要删除吗？', '提示', {type: 'warning'});                
                //要接着删除后端数据库中的记录
                let id =  this.tableData[index].id; //要删除记录的id 
                await deleteGoodsById({id});
                this.tableData.splice(index, 1);
                this.$message.success('删除成功');
            } catch (error) {
                console.log(error);
            }  
               
        },
        
        
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.fileList=[];
            this.fileList.push({name:this.form.name,url:this.ApiBaseURL + this.form.image})
            console.log(this.form); //================


            this.editVisible = true;
        },
        // 保存编辑
        async saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
            //接下来要同时更新后端数据库表中的数据
            try{
               let result =  await updateGoods(this.form)
               console.log(result)
            }
            catch(error){
                this.$message("错误",error);
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getTableData();
        },


    //================图片上传 
    handleSuccess(result) {
      //图片上传成功 result是接口返回数据{code msg ,url}
      this.form.image  = result.url
    },
    handleExceed() {
      //图片上传超过数量限制
      this.$message.error("上传图片不能超过1张!");      
    }, 
    handlePreview() {
      //预览图片时调用        
      this.dialogVisible = true;
    },
    handleRemove() {
      //移除图片      
      this.form.image  = ''    
    },


    submitUpload() {
        this.$refs.upload.submit();
    },

    handleUploadChange(file, fileList) {
        },


    beforeUpload(file) {
      //文件上传之前调用做一些拦截限制      
      const isJPGPNG = (file.type === 'image/jpg' || file.type === 'image/png') ;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG\PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPGPNG && isLt2M;
    },
    
    imgUploadError(err) {
      //图片上传失败调用      
      this.$message.error(`上传图片失败!错误信息：${err}`);
    },

     

    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-image {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

</style>